package com.ramos.kuaixiao.network;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.MyView.SelfDialog;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.File;
import java.util.concurrent.Executors;

public class DownloadUpdateFileTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "DownloadUpdateFile";
    private final static String DOWNLOAD_APP_NAME = "app.apk";
    static Activity mContext;
    int type;
    @Override
    protected void onPreExecute() {

    }

    public DownloadUpdateFileTask(Activity context, int i){
        mContext = context;
        type = i;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            //获取服务器版本文件
            getUpdateFile();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getUpdateFile() {
        try {
            String url = "";
            if(type == 1){
                url = NetUtils.GET_UPDATE_FILE;
            } else if(type == 2){
                url = NetUtils.GET_UPDATE_CUSTOMER_FILE;
            }
            Log.d(TAG, "getUpdateFile:path " + url);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(1200000);
            client.get(url, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "getUpdateFile:result=" + result);
                        int serverVersion = jsonObejct.getInteger("versionCode");
                        Log.d(TAG, "getUpdateFile:serverVersion=" + serverVersion);
                        int curVersion = Utils.getVersion(App.mContext);

                        if(serverVersion > curVersion){
                            if(App.mShowDialog == 0) {
                                Looper.prepare();
                                Log.d(TAG, "App.mShowDialog=" + App.mShowDialog);
                                final SelfDialog builder = new SelfDialog(mContext);
                                App.mShowDialog = 1;
                                builder.setTitle("应用更新提示");
                                builder.setMessage("当前应用有新本，是否更新？" +
                                        "更新内容包括:1、库存同步更新");
                                builder.setNoOnclickListener("拒绝", new SelfDialog.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        builder.dismiss();
                                        App.mShowDialog = 0;
                                        App.mIsUpdate =false;
                                    }
                                });
                                builder.setYesOnclickListener("更新", new SelfDialog.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        builder.dismiss();
                                        App.mIsUpdate =false;
                                        File apkFile = new File(FileUtil.getApkPath(App.mContext), DOWNLOAD_APP_NAME);
                                        if (apkFile.exists()) {
                                            update();
                                        } else {
                                            ToastUtils.show("开始下载,下载完成后请安装应用！");
                                            DownloadTask product12 = new DownloadTask(mContext, type);
                                            product12.executeOnExecutor(Executors.newCachedThreadPool());
                                        }
                                        hideKeyboard();
                                    }
                                });
                                builder.show();
                                Looper.loop();
                            }
                        } else {
                            File apkFile = new File(FileUtil.getApkPath(App.mContext), DOWNLOAD_APP_NAME);
                            if(apkFile.exists()){
                                apkFile.delete();
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   private void hideKeyboard() {
       View view = mContext.getWindow().peekDecorView();
       if (view != null) {
           InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
           inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
       }
   }

    /**
     * 下载应用
     *
     * @author Administrator
     */
    class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private int mType;

        public DownloadTask(Context context, int type) {
            this.context = context;
            mType = type;
        }

        @Override
        protected String doInBackground(String... sUrl) {

            try {
                App.mIsUpdate = true;
                String url = "";
                if(mType == 1){
                    url = NetUtils.GET_UPDATE_APK;
                } else if(mType == 2){
                    url = NetUtils.GET_UPDATE_CUSTOMER_APK;
                }
                Log.d(TAG, "getUpdateFile:path " + url + "  App.mIsUpdate:"+App.mIsUpdate);
                SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
                // 创建请求参数的封装的对象
                client.setTimeout(12000000);
                client.get(url, new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                        //判断状态码
                        try {
                            App.APK_URL = Utils.getAPKFile(responseBody, FileUtil.getApkPath(App.mContext), DOWNLOAD_APP_NAME);
                            if(!StringUtil.isEmpty(App.APK_URL)){
                                Log.d(TAG, "APK_URL:" +  App.APK_URL);
                                update();
                            }
                            App.mIsUpdate = false;
                            App.mShowDialog = 0;
                        } catch (Exception e) {
                            App.mIsUpdate = false;
                            App.mShowDialog = 0;
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                                          byte[] responseBody, Throwable error) {
                        App.mIsUpdate = false;
                        App.mShowDialog = 0;
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                App.mIsUpdate = false;
                App.mShowDialog = 0;
            }
            App.mIsUpdate = false;
            App.mShowDialog = 0;
            return null;
        }
    }

    private void update() {
        //安装应用
        Log.d(TAG, "update");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(FileUtil.getApkPath(App.mContext), DOWNLOAD_APP_NAME)),
                "application/vnd.android.package-archive");
        //mContext.startActivity(intent);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivityForResult(intent, 0);// 如果用户取消安装的话,
        // 会返回结果,回调方法onActivityResult
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
